﻿using System;
using System.IO;
using System.Windows;

namespace Silverlight.Media.Encoder
{
    public static class EncoderProfileGenerator
    {
        private static string m_encoderTemplateVideo;
        private static string m_encoderTemplateAudioVideo;

        private static string PROFILE_TEMPLATE_KEY_VIDEO_BITRATE = "%VIDEO_BITRATE%";
        private static string PROFILE_TEMPLATE_KEY_VIDEO_WIDTH = "%VIDEO_WIDTH%";
        private static string PROFILE_TEMPLATE_KEY_VIDEO_HEIGHT = "%VIDEO_HEIGHT%";
        private static string PROFILE_TEMPLATE_VIDEO_URI_PATH = "Silverlight.Media.Encoder;component/wmencprofile_template.prx";
        private static string PROFILE_TEMPLATE_AUDIO_VIDEO_URI_PATH = "Silverlight.Media.Encoder;component/wmencprofile_template_audio_video.prx";

        static EncoderProfileGenerator()
        {
            LoadEncoderProfileData();
        }

        private static void LoadEncoderProfileData()
        {
            m_encoderTemplateVideo = GetResourceString(PROFILE_TEMPLATE_VIDEO_URI_PATH);
            m_encoderTemplateAudioVideo = GetResourceString(PROFILE_TEMPLATE_AUDIO_VIDEO_URI_PATH);
        }

        private static string GetResourceString(string resourcePath)
        {
            var pathUri = new Uri(resourcePath, UriKind.Relative);
            var streamResourceInfo = Application.GetResourceStream(pathUri);

            return new StreamReader(streamResourceInfo.Stream).ReadToEnd();
        }

        public static string GetProfileVideo(int videoWidth, int videoHeight, int videoBitrate)
        {
            string profile = m_encoderTemplateVideo;

            profile = profile.Replace(PROFILE_TEMPLATE_KEY_VIDEO_BITRATE, videoBitrate.ToString());
            profile = profile.Replace(PROFILE_TEMPLATE_KEY_VIDEO_WIDTH, videoWidth.ToString());
            profile = profile.Replace(PROFILE_TEMPLATE_KEY_VIDEO_HEIGHT, videoHeight.ToString());

            return profile;
        }

        public static string GetProfileAudioVideo(int videoWidth, int videoHeight, int videoBitrate)
        {
            string profile = m_encoderTemplateAudioVideo;

            profile = profile.Replace(PROFILE_TEMPLATE_KEY_VIDEO_BITRATE, videoBitrate.ToString());
            profile = profile.Replace(PROFILE_TEMPLATE_KEY_VIDEO_WIDTH, videoWidth.ToString());
            profile = profile.Replace(PROFILE_TEMPLATE_KEY_VIDEO_HEIGHT, videoHeight.ToString());

            return profile;
        }
    }
}
